/*
 * Copyright (c) 2010 All Inclusive Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.allinclusive.fw.web.ajax.converter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.allinclusive.fw.core.config.GlobalConfig;
import com.googlecode.allinclusive.fw.web.ajax.exception.AjaxHandleException;

/*
 * (no-javadoc)
 */
public class JsonConverter implements ResponseConverter {

    private static final Log log = LogFactory.getLog(JsonConverter.class);
    
    public static final String ENCODING = GlobalConfig.DEFAULT_ENCODING;
    
    /*
     * (no-javadoc)
     * @param obj 
     * @param request
     * @param response
     */
	public String convert(Object obj, HttpServletRequest request, HttpServletResponse response) {
		// JSON形式字符串
        String output;

        // 转换成JSON形式字符串
        if (obj instanceof Enum || obj instanceof Collection || obj instanceof Object[]) {
			JSONArray json = JSONArray.fromObject(obj);

			if (log.isDebugEnabled()) {
				log.debug("JSON:" + json.toString());
			}

			output = json.toString();
		} else {
			JSONObject json = JSONObject.fromObject(obj);
			if (log.isDebugEnabled()) {
				log.debug("JSON:" + json.toString());
			}
			output = json.toString();
		}

        // 写入response流
		PrintWriter writer;
		try {
			// Http头设置
			response.setContentType("text/html; charset=" + ENCODING);
			response.addHeader("Content-Type", "text/html");
			response.addHeader("charset", ENCODING);
			response.addHeader("Cache-Control", "no-cache");
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Expires", "0");

			writer = response.getWriter();
			writer.print(output);
			//writer.close();
		} catch (IOException e) {
			throw new AjaxHandleException(e);
		}

		return null;
	}

}
